<?php
class Adm_Action_Helper_Acl extends Zend_Controller_Action_Helper_Abstract
{
	private $_session;
	private $_acl;
	private $_role;
	
	public function init()
	{
		$this->_session = Zend_Registry::get('session');	
		$this->_initAcl();		
	}
	
	public function preDispatch()
	{
		$controler = $this->getActionController();
		$controler->getHelper('LoadEntities')->loadEntities();
		$this->_setRole();
		
		$controler->view->navigation()->setAcl( $this->_acl );
		$controler->view->navigation()->setRole( $this->_role);
		
		$resource	= $this->getRequest()->getParam('controller');
		$action		= $this->getRequest()->getParam('action');
		
		if ( ! $this->isAllowed( $resource, $action)){
		
			$controler->getHelper('Redirector')
						->gotoRouteAndExit( array('controller'=>'error', 'action'=>'denied') );
			
		}
	}
	
	public function isAllowed( $resource, $action)
	{
		return $this->_acl->isAllowed( $this->_role , $resource, $action);
	}
	
	
	private function _setRole()
	{
	    
		if ( !isset($this->_session->userId) ){
		
			$this->_role = 'guest';
		
		}else{
			
			$this->_role = $this->getActionController()->user->getType();
			
		}
		
	}
	
	private function _initAcl()
	{
		$acl = new Zend_Acl();
		
		//Roles
		$acl->addRole(new Zend_Acl_Role('guest'))
			->addRole(new Zend_Acl_Role('editor'), 'guest')
			->addRole(new Zend_Acl_Role('admin'), 'editor')
      		->addRole(new Zend_Acl_Role('fulladmin'), 'admin');
		
		//Resources
		$acl->add(new Zend_Acl_Resource('error'))
			->add(new Zend_Acl_Resource('authentication'))
			->add(new Zend_Acl_Resource('index'))
			->add(new Zend_Acl_Resource('users'))
			->add(new Zend_Acl_Resource('categories'))
			->add(new Zend_Acl_Resource('cities'))
			->add(new Zend_Acl_Resource('questions'))
			->add(new Zend_Acl_Resource('reasons'))
			->add(new Zend_Acl_Resource('reason-families'));
		
		/** Permissions */
		$acl->allow('guest'		, 'error')
			->allow('guest'		, 'authentication')
			
			->allow('editor'	, 'index')
			->allow('editor'	, 'questions')
			
		    ->allow('admin'		, 'categories')
		    ->allow('admin'		, 'cities')
		    ->allow('admin'		, 'reasons')
		    ->allow('admin'		, 'reason-families')
		    
		    ->allow('fulladmin'	, 'users');
			
		$this->_acl = $acl;	
		Zend_Registry::set('acl', $acl);	
	
	}

}